package Demo2;
//增删查改时间复杂度都是O（1）
//HashMap是考试重点！！！
//浪费空间来换取时间的过程
public class HashBuck {
    static class Node {
        public int key;
        public int val;

        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }
        public  Node[] arr;
        public int useSized;

        public HashBuck() {
            this.arr = new Node[10];
        }
        public void put(int key,int val){
             int index = key % arr.length;
             Node node = new Node(key,val);
             Node cur = arr[index];
//             while(cur.next != null){
//                 cur = cur.next;
//             }
//             cur.next = node;
            //先遍历一遍整体的链表是否存在当前key
            while(cur != null){
                if(cur.key == key){
                    cur.val = val;
                    return;
                }
                cur = cur.next;
            }
            //没有这个key
            node.next = arr[index];
            arr[index] = node;
            useSized++;
            if(loadFactor()>=0.75){
                resize();
            }
        }
    //扩容需要注意什么？
    // 把所有的元素都要重新进行哈希
        private void resize() {
            Node[] tmpArr = new Node[arr.length*2];
            //遍历原来的数组  将所有的元素   《重新哈希》到新的数组中
            for (int i = 0; i < arr.length; i++) {
                Node cur = arr[i];
                while(cur != null){
                    //记录下当前节点的下一个节点
                    Node curNext = cur.next;
                    int newIndex = cur.key % tmpArr.length;
                    //头插法
                    cur.next = tmpArr[newIndex];
                    tmpArr[newIndex] = cur;
                    cur = curNext;
                }
            }
            arr = tmpArr;
        }

        private double loadFactor(){
            return useSized*1.0 / arr.length;
        }
        public  int get(int key){
            int index = key % arr.length;
            Node cur = arr[index];
            while(cur != null){
                if (cur.key == key){
                    return cur.val;
                }
                cur = cur.next;
            }
            return -1;
        }
}
